package com.weixing.core.util.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.weixing.core.util.XmlUtil;

/**
 * 针对ErrorCode.xml文件的实现
 * 
 * @author Fu Dongwei
 * @Date 2015-02-06
 * @version 1.0
 */
public class XmlUtilForImpl implements XmlUtil {

	private static final Log LOGGER = LogFactory.getLog(XmlUtilForImpl.class);

	// 获取所有错误编码并组装成Map
	private Map<Integer, String> GetErrors() {
		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("ErrorCode.xml");
		// 读取输入流
		SAXReader reader = new SAXReader();
		Map<Integer, String> errorMap = null;
		Document document;
		try {
			// 读取文件流
			document = reader.read(inputStream);
			// 得到xml根元素
			Element root = document.getRootElement();
			// 得到根元素的所有子节点
			errorMap = new HashMap<Integer, String>();
			Element element = null;
			// 遍历所有子节点
			for (@SuppressWarnings("rawtypes")
			Iterator iterator = root.elementIterator("Error"); iterator
					.hasNext();) {
				element = (Element) iterator.next();
				// 读取错误编码
				int code = Integer.parseInt(element.elementText("Code"));
				// 读取错误消息
				String msg = element.elementText("Msg");
				errorMap.put(code, msg);
			}
			// 释放资源
			inputStream.close();
			inputStream = null;
		} catch (DocumentException e1) {
			LOGGER.error("读取XML文件失败！" + e1.getMessage());
		} catch (IOException e) {
			LOGGER.error("文件流操作失败！" + e.getMessage());
		}
		return errorMap;
	}

	// 根据错误编码返回错误消息
	@Override
	public String GetMsgByCode(int code) {
		Map<Integer, String> errorCodes = GetErrors();
		if (!errorCodes.isEmpty()) {
			return errorCodes.get(code);
		} else {
			return "错误列表中为包含该未知错误！";
		}
	}
}
